/*===============================
 *Title      :  FileTreeTraverser.java
 *Created  :[ 2012-3-21 下午3:55:05 ] by fanlt
 * ==============================
 * Description:  基于深度遍历算法实现
 * Copyright  :  Copyright (c) 2012
 * Company    :  Flyfot
 * @author  <a href="fanlt@flyfot.cn">fanlt</a>
 *
 */
package org.zxstudio.encrypt.tree;

import java.io.File;
import java.io.IOException;
import java.util.Stack;

import org.zxstudio.encrypt.utils.Constant;

import android.util.Log;

/**
 * @author fan
 * 
 */
public class FileTreeTraverser {
	private static final String TAG = "FileTreeTraverser";
	private static final boolean DEBUG = true;

	private String mRealParent = null;
	Stack<File> mStack = new Stack<File>();
	String name = null;

	public boolean encryptFolder(File file) {
		FileBean bean = new FileBean(file, Constant.ENCRYPT_ROOT_PATH);
		mRealParent = file.getParent();
		name = file.getName();
		File target = new File(Constant.ENCRYPT_ROOT_PATH);
		if (!target.exists()) {
			target.mkdir();
		}
		
		boolean result = mvFolderTree(bean);
		return result;
	}
	
    /**
     * 
	 * 移动树形菜单到加密目录
	 * 
     * @param node
     * @return
     */
    private boolean mvFolderTree(FileBean node) {
    	if (node != null) {
    		File file  = new File(node.getStubPath());
    		if (!file.exists()) {
    			if (file.mkdir()) {
    				Log.v(TAG,file.getPath() + " create sucess !");
    			}
    		}
    	}
    	for (FileBean bean : node.getChildList()) {
    		if (bean.isFile()) {
    			Log.v(TAG, bean.getPath() + "已经被删除");
				File file = new File(bean.getStubPath());
				if (!file.exists()) {
					try {
						file.createNewFile();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				bean.getFile().delete();
    		} else {
    			if(!mvFolderTree(bean)) {
    				return false;
    			}
    		}
    	}
    	
    	if (!node.getFile().delete()) {
    		return false;
    	}
    	
    	return true;
    }
}
